package com.egao.api.controller;


import com.egao.common.core.annotation.OperLog;
import com.egao.common.core.damon.utils.HttpsUtils;
import com.egao.common.core.web.BaseController;
import com.egao.common.core.web.JsonResult;
import com.egao.common.system.entity.User;
import com.egao.gzh.service.GzhToken;
import com.egao.gzh.service.Wxservice;
import com.egao.gzh.utils.AesException;
import com.egao.gzh.utils.WXPublicUtils;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.dom4j.DocumentException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * api登录相关接口
 * Created by wangfan on 2019-05-29 下午 3:43.
 * http://localhost/swagger-ui.html
 * http://192.168.1.110/swagger-ui.html
 */
@RequestMapping("/api/nt/login")
@RestController
public class GzhController extends BaseController {

//    @Qualifier("jdbcTokenStore")
//    @Autowired
//    private TokenStore tokenStore;

    /**
     * 微信公众平台token
     */
    @GetMapping("/gzh")
    public String gzhValidate(String signature, String timestamp,
                                      String nonce, String echostr) throws AesException {
        if (WXPublicUtils.verifyUrl(signature, timestamp, nonce)) {
            System.out.println("公众号验证成功!");
            return echostr;
        }
        return null;
    }

    @PostMapping(value = "gzh")
    public void processMsg(HttpServletRequest request, HttpServletResponse response) throws IOException, DocumentException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Wxservice wxservice = new Wxservice();
        // 调用核心服务类接收处理请求
        Map<String, String> requestMap = wxservice.parseRequest(request.getInputStream());
        System.out.println(requestMap);
        //准备回复的数据包
        String resXml = wxservice.getRespose(requestMap);
//                "<xml>" +
//                "<ToUserName><![CDATA["+requestMap.get("FromUserName")+"]]></ToUserName>" +
//                "<FromUserName><![CDATA["+requestMap.get("ToUserName")+"]]></FromUserName>" +
//                "<CreateTime>"+ System.currentTimeMillis()/1000 +"</CreateTime>" +
//                "<MsgType><![CDATA[text]]></MsgType>" +
//                "<Content><![CDATA[why?]]></Content>" +
//                "</xml>";

        PrintWriter out = response.getWriter();
        System.out.println(resXml);
        out.print(resXml);
        out.flush();
        out.close();
//        ServletInputStream is = request.getInputStream();
//        byte[] b = new byte[1024];
//        int len;
//        StringBuilder sb = new StringBuilder();
//        while ((len=is.read(b))!=-1) {
//            sb.append(new String(b, 0, len));
//        }
    }

    /**
     * 分页查询列表
     */
    @OperLog(value = "创建ticket,并得到image", desc = "")
    @ResponseBody
    @RequestMapping("/createTicketImage")
    public JsonResult createTicketImage(User user) throws Exception{
        GzhToken gt = new GzhToken();
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="+ gt.getAccessToken();
        //生成临时字符串二维码
        String data = "{\"expire_seconds\": 2400, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"userId="+user.getUserId()+"\"}}}";
        String post = HttpsUtils.post(url, data);
        String ticket = JSONObject.fromObject(post).getString("ticket");

        String image = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ ticket;
        return JsonResult.ok().put("image",image);
    }


}
